/**
 * @namespace Archetype.methodBuilders.eventListeners
 * Automatic event Listener for your component. Just add a "on" prefix to a method for it to
 * automatically listen for the event named after this prefix.
 *
 * The listener will get the event in first parameter, and can get the data posted by the event
 * with (say we will use the variable "event" as first parameter) event.event_data.data
 *
 * @example:
 * 	- onHello: function(event){...} -> listen for event "Hello"
 * 	- 'onHello World': function(event){...} -> listen for event "Hello World"
 *
 */
$N("Archetype.methodBuilders.eventListeners", {
	regexp:"^on.*",
	/**
	 * Acts on the Component definition method methodName (that matches "this.regexp")
	 *
	 * @param {ComponentDefinition} component
	 * @param {Function} methodName
	 */
	build: function (component, methodName){
		//Get event name
		var evtName=/^on(.*)/.exec(methodName)[1];
		
		var listener = function(data){
			//Logger.log("["+component._private._definition[methodName].name+"]","received event ", evt.event_data.event_name, " with data :", evt.event_data.data);
			Logger.log("["+component._private._definition[methodName].name+"]","received event ", arguments);
			component[methodName](evtName, data);
		}.bind(component._private); //must refer to the real instance ?
		
		//Register this method as a listener for the Event
		//Archetype.Events.addEventListener(evtName, listener);
		Archetype.engine.observe(evtName, listener);
		
		//Store listening information in the _destroy table in order
		//to be able to diconnect it later
		if(!$exist(component._private._destroy)) {
			component._private._destroy = $A();
		}
		component._private._destroy.push("archetypeEvent");
		component._private._destroy.push(evtName);
		component._private._destroy.push(listener);
		
		Logger.log("["+component._private._definition[methodName].name+"]", "Registering event listener");
	}
});